package by.grsu.og.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.og.entity.Library;
import by.grsu.og.table.LibraryTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

/**
 * @author dmitry_zhivushko
 * @since Sep 28, 2014
 */
public class LibraryDao extends AbstractDao<LibraryTable, Library> {


	public LibraryDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Library newLibrary) {
		// set ID
		newLibrary.setId(getNextId());
		// get existing data
		final LibraryTable libraryTable = deserializeFromXml();
		// add new row
		libraryTable.getRows().add(newLibrary);
		// save data
		serializeToXml(libraryTable);
	}

	@Override
	public void update(final Library entity) {
		// get existing data
		final LibraryTable libraryTable = deserializeFromXml();
		// find by ID
		for (final Library row : libraryTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setCost(entity.getCost());
				row.setCategory(entity.getCategory());
				break;
			}
		}
		// save updated table
		serializeToXml(libraryTable);
	}

	@Override
	public Library get(final Serializable id) {
		// get existing data
		final LibraryTable libraryTable = deserializeFromXml();
		// find by ID
		for (final Library row : libraryTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Library> getAll() {
		// get existing data
		final LibraryTable libraryTable = deserializeFromXml();
		return libraryTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		// get existing data
		final LibraryTable libraryTable = deserializeFromXml();
		// find by ID
		Library toBeDeleted = null;
		for (final Library row : libraryTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		libraryTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(libraryTable);
	}

	@Override
	protected Class<LibraryTable> getTableClass() {
		return LibraryTable.class;
	}

}
